package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;

import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.ContactBean;
import com.ctyon.watchmanager.databinding.FragmentSosBinding;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.SosPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.orhanobut.logger.Logger;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class SosFragment extends BaseFragment {

    public static final String TAG = "SosFragment";

    private FragmentSosBinding mBinding;
    private boolean mSosConfig;

    public static SosFragment newInstance() {
        final SosFragment fragment = new SosFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_sos, container, false);
        mBinding.setSosPresenter(sosPresenter);

        mSosConfig = BasicApp.getInstance().getWatch().getSosConfig() == 1;
        mBinding.setConfig(mSosConfig);

        mBinding.sosText1.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null != s){
                    mBinding.sosText1.setSelection(s.toString().length());
                }
            }
        });
        mBinding.sosText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null != s){
                    mBinding.sosText2.setSelection(s.toString().length());
                }
            }
        });
        mBinding.sosText3.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null != s){
                    mBinding.sosText3.setSelection(s.toString().length());
                }
            }
        });

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        String sosStr = BasicApp.getInstance().getWatch().getSos();
        if (!DataUtil.isEmptyAnd(sosStr)) {
            String[] strings = sosStr.split("&");
            for (int i = 0; i < strings.length; i++) {
                if (DataUtil.isEmptyOr(strings[i]) || strings[i].equals("null")){
                    continue;
                }
                if (i == 0) {
                    mBinding.setSos1(strings[0]);
                } else if (i == 1) {
                    mBinding.setSos2(strings[1]);
                } else if (i == 2) {
                    mBinding.setSos3(strings[2]);
                }
            }
        }

    }

    private final SosPresenter sosPresenter = new SosPresenter() {
        @Override
        public void onSaveBtClick(String sos1, String sos2, String sos3) {
            Logger.t(LTAG).i("sos : " +  sos1 + "、" + sos2+ "、" + sos3);
            final String method = "sosNumber";
            if (NetService.getInstance().isDisable(method)) {
                TSnackbarUtil.TSBError(getActivity(), "请稍候...");
                return;
            }
            boolean isEmpty = false;
            if (DataUtil.isEmptyAnd(sos1, sos2, sos3)) {
                isEmpty = true;
            }
            boolean finalIsEmpty = isEmpty;
            NetService.getInstance()
                    .method(method)
                    .sosNumber(BasicApp.getInstance().getManager().getManagerId(),
                            BasicApp.getInstance().getWatch().getMeid(),
                            sos1, sos2, sos3)
                    .timeout(10, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.d("onSuccess : " + responseEntity.toString());
                            if (finalIsEmpty) {
                                TSnackbarUtil.TSBSuccess(getActivity(), "SOS号码已清空");
                                BasicApp.getInstance().getWatch().setSos("");
                            } else {
                                TSnackbarUtil.TSBSuccess(getActivity(), "操作成功");
                                String[] sosArr = new String[3];
                                if (!DataUtil.isEmptyOr(sos1) && !sos1.equals("null")){
                                    sosArr[0] = sos1;
                                }
                                if (!DataUtil.isEmptyOr(sos2) && !sos2.equals("null")){
                                    sosArr[1] = sos2;
                                }
                                if (!DataUtil.isEmptyOr(sos3) && !sos3.equals("null")){
                                    sosArr[2] = sos3;
                                }
                                StringBuilder builder = new StringBuilder();
                                for (int i = 0; i < sosArr.length; i++) {
                                    if(DataUtil.isEmptyOr(sosArr[i])){
                                        continue;
                                    }
                                    if (builder.length() > 0){
                                        builder.append("&");
                                    }
                                    builder.append(sosArr[i]);
                                }
                                Logger.d("setSos : " + builder.toString());
                                BasicApp.getInstance().getWatch().setSos(builder.toString());
                            }
                        }

                        @Override
                        public String onOver() {
                            return method;
                        }
                    });
        }

        @Override
        public void onCheckedChanged(CompoundButton button, boolean checked) {
            if (mSosConfig == checked) {
                return;
            }
            NetService.getInstance()
                    .sosConfig(BasicApp.getInstance().getManager().getManagerId(),
                            BasicApp.getInstance().getWatch().getMeid(),
                            checked)
                    .timeout(10, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.d("onSuccess : " + responseEntity.toString());
                            TSnackbarUtil.TSBSuccess(getActivity(), checked ? "开启成功" : "关闭成功");
                            mSosConfig = checked;
                            BasicApp.getInstance().getWatch().setSosConfig((byte) (mSosConfig ? 1 : 0));
                            mBinding.setConfig(checked);
                        }

                        @Override
                        public void onErrorE(Throwable e) {
                            TSnackbarUtil.TSBSuccess(getActivity(), checked ? "开启失败" : "关闭失败");
                            mSosConfig = !checked;
                            mBinding.setConfig(mSosConfig);
                        }
                    });
        }
    };

}
